package com.sw.haruka.module.ftp

import android.view.View
import com.sw.haruka.R
import com.sw.haruka.dal.HarukaConfig
import com.sw.haruka.databinding.FtpActBinding
import com.sw.haruka.module.ftp.manager.FtpServerManager
import com.sw.haruka.helper.utils.NetUtils
import com.sw.haruka.module.title.TitleMode
import com.sw.haruka.module.title.TransformerTitleFragment
import com.sw.haruka.view.base.BaseActivity
import com.sw.haruka.module.ftp.viewmodel.FtpViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * Created by Swsbty on 2021/05/01
 */
class FtpActivity : BaseActivity<FtpActBinding>(), FtpServerManager.FtpObserver {

    private val mViewModel by viewModel<FtpViewModel>()

    override fun initView() {
        mBinding.apply {
            vm = mViewModel
            presenter = this@FtpActivity
        }
        supportFragmentManager.beginTransaction()
            .add(R.id.title_ll, TransformerTitleFragment(TitleMode.FTP_BAR))
            .commit()
        FtpServerManager.getInstance().addObserver(this)
    }


    override fun loadData(isRefresh: Boolean) {
        if (FtpServerManager.getInstance().isOpen) {
            mViewModel.startInfo(NetUtils.getLocalIP(mContext))
        } else {
            mViewModel.stopInfo()
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.btn_start -> FtpServerManager.getInstance().start(HarukaConfig.ROOT_PATH)
            R.id.btn_stop -> FtpServerManager.getInstance().stop()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        FtpServerManager.getInstance().removeObserver(this)
    }


    override fun layoutId() = R.layout.ftp_act

    override fun statusChange(offset: Boolean) {
        if (offset) {
            mViewModel.startInfo(NetUtils.getLocalIP(mContext))
        } else {
            mViewModel.stopInfo("FTP服务已关闭")
        }
    }
}